package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.dto.ChatGroupDto;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.SearchRequestMessage;
import org.aeon.message.response.SearchResponseMessage;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.List;

/**
 * @author: MissingAeon
 * @date: 2024/2/22 16:17
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
public class SearchRequestHandler extends SimpleChannelInboundHandler<SearchRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SearchRequestMessage msg) throws Exception {
        final SearchResponseMessage resMsg = new SearchResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final String keyword = msg.getKeyword();
        resMsg.setResponse(true, "包含" + keyword + "的结果");
        // 获取相关用户
        final List<UserDto> users = UserServiceFactory.getService().fuzzySearch(keyword);
        // 添加状态
        users.forEach(item -> item.setLeave(SessionFactory.getSession().getChannel(item.getId()) == null));
        resMsg.setUsers(users);
        // 获取相关群
        final List<ChatGroupDto> groups = ChatGroupServiceFactory.getService().fuzzySearch(keyword);
        resMsg.setGroups(groups);
        ctx.writeAndFlush(resMsg);
        log.debug("本次查询用户{}个,群聊{}个", users.size(), groups.size());
    }
}
